using Microsoft.AspNetCore.Mvc;
using RankDemo.WebApi.Dtos;
using RankDemo.WebApi.Entities;
using RankDemo.WebApi.Services;

namespace RankDemo.WebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class CustomerController : ControllerBase
    {
        private readonly ICustomerService _customerService;
        private readonly IRankService _rankService;

        public CustomerController(
            ICustomerService customerService,
            IRankService rankService)
        {
            _customerService = customerService;
            _rankService = rankService;
        }

        [HttpGet]
        public List<CustomerDto> GeList()
        {
            var customers = _customerService.GetAll();
            return customers.Select(c => new CustomerDto()
            {
                CustomerId = c.CustomerId,
                Score = c.Score,
            }).ToList();
        }

        [HttpPost("{customerId}/score/{score}")]
        public decimal PatchScore(long customerId, int score)
        {
            var customer = _customerService.GetCustomer(customerId);
            if (customer == null)
            {
                customer = new Customer()
                   .SetCustomerId(customerId)
                   .ChangeScore(score);
                _customerService.CreateCustomer(customer);
                _rankService.CreateCustomer(customer);
                return customer.Score;
            }

            _rankService.UpdateCustomerScore(customer, score);

            return customer.Score;
        }
    }
}